//
//  ProductChoosePopView.m
//  sensen_ios
//
//  Created by pro on 16/2/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ProductChoosePopView.h"

// 控制器
#import "LoginVC.h"
#import "ConfirmOrderVC.h" // 确认订单页面，立即购买就直接跳过去

// 数据
#import "CartProductModel.h" // 购物车商品model
#import "StoreDiscountModel.h" // 店铺优惠
// 辅助类
#import "ProductInfoHandle.h"
#import "ZoomImageView.h"

// 单元格
#import "CollectSkuCell.h" // 规格选择的单元格
#import "AmountCell.h" // 选择数量的单元格

#define sku_selected_color SS_NAVI_ORANGE_LIGHT_COLOR
#define sku_cannot_select_color [UIColor colorWithWhite:0.98 alpha:1]
#define sku_can_select_color [UIColor colorWithWhite:0.95 alpha:1]

@interface ProductChoosePopView () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, AmountModifyViewDelegate>
{
    NSMutableArray *_skuSelectModelArray; // 用于布局单元格（有几组规格就有几个元素）
    NSMutableArray *_skuSelectIdArray; // 用于获得选中的skuId（1：1），拼接数组
    SkuModel *_selectedModel; // 选中的某种规格的商品model，用于添加购物车，或立即购买
    NSInteger _selectCount; // 选中的数量
}
// 视图
@property (nonatomic, strong) UIView *bgView; // 背景黑色半透明视图
@property (nonatomic, strong) UIView *popView; // 弹出视图

// 弹出视图的子视图
@property (nonatomic, strong) ZoomImageView *iconView; // 商品图标视图
@property (nonatomic, strong) UILabel *priceLabel; // 价格label
@property (nonatomic, strong) UILabel *stockLabel; // 库存label
@property (nonatomic, strong) UILabel *notesLabel; // "请选择规格"label（注释label）
@property (nonatomic, strong) UIButton *cancelButton; // 取消按钮

@property (nonatomic, strong) UICollectionView *collectionView; // 规格展示视图

@property (nonatomic, strong) UIButton *confirmButton; // 确定按钮（点击查看规格是显示这个，否则显示下面的两个按钮）
@property (nonatomic, strong) UIButton *addToCartButton; // 加入购物车
@property (nonatomic, strong) UIButton *buyNowButton; // 立即购买


@end

@implementation ProductChoosePopView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.hidden = YES; // 初始设置为隐藏
        
        [self _initViews];
    }
    
    return self;
}

#pragma mark -- 创建视图 --
- (void)_initViews {
    
    [self _createBgView];
    [self _createPopView];
    
}
// 创建背景视图
- (void)_createBgView {
    
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    _bgView.backgroundColor = [UIColor blackColor];
    _bgView.alpha = 0;
    [self addSubview:_bgView];
    
    // 给背景遮罩视图添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidden)];
    [_bgView addGestureRecognizer:tap];
}
// 创建弹出视图
- (void)_createPopView {
    
    CGFloat x,y,width,height;
    x = 0;
    width = self.width;
    height = SCREEN_HEIGHT * 0.8;
    y = self.height;
    // 整个弹出视图
    _popView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _popView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_popView];

    // 弹出视图的子视图
    // 1.商品图标视图
    x = 10;
    y = -10;
    width = SCREEN_WIDTH * 0.25;
    height = width;
    _iconView = [[ZoomImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _iconView.image = DEFAULT_IMAGE;
    [_popView addSubview:_iconView];
    
    // 2.价格label
    x = _iconView.right + 10;
    y = 10;
    // 50：右侧取消按钮，10：和图标的间距
    width = _popView.width - _iconView.right - 10 - 50;
    height = 20;
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _priceLabel.font = FONT(14);
    _priceLabel.text = @"￥0";
    _priceLabel.textColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    _priceLabel.textAlignment = NSTextAlignmentLeft;
    [_popView addSubview:_priceLabel];
    
    // 2.库存label
    y = _priceLabel.bottom;
    _stockLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _stockLabel.font = FONT(14);
    _stockLabel.text = @"库存0件";
    _stockLabel.textColor = [UIColor darkGrayColor];
    _stockLabel.textAlignment = NSTextAlignmentLeft;
    [_popView addSubview:_stockLabel];
    
    // 3."请选择规格"label
    y = _stockLabel.bottom;
    _notesLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _notesLabel.font = FONT(14);
    _notesLabel.text = @"请选择规格分类";
    _notesLabel.textColor = [UIColor darkGrayColor];
    _notesLabel.textAlignment = NSTextAlignmentLeft;
    [_popView addSubview:_notesLabel];

    // 4.取消按钮
    width = 25;
    height = width;
    x = SCREEN_WIDTH - 10 - width;
    y = 10;
    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.frame = CGRectMake(x, y, width, height);
    [_cancelButton setBackgroundImage:[UIImage imageNamed:@"取消"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [_popView addSubview:_cancelButton];
    
    // 5.下方按钮
    [self _createButton];
    
    // 6.规格展示 collectionView
    [self _createCollectionView];
    
}

- (void)_createButton {
    CGFloat x = 0;
    CGFloat y = _popView.height - 49;
    CGFloat width = self.width;
    CGFloat height = 49;
    // 确定按钮
    _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _confirmButton.frame = CGRectMake(x, y, width, height);
    _confirmButton.backgroundColor = RED_COLOR;
    [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmButton addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [_popView addSubview:_confirmButton];
    
    // 加入购物车
    width = self.width / 2;
    _addToCartButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _addToCartButton.frame = CGRectMake(x, y, width, height);
    _addToCartButton.backgroundColor = ORANGE_COLOR;
    [_addToCartButton setTitle:@"加入购物车" forState:UIControlStateNormal];
    [_addToCartButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_addToCartButton addTarget:self action:@selector(addToCartAction:) forControlEvents:UIControlEventTouchUpInside];
    [_popView addSubview:_addToCartButton];
    
    // 立即购买
    x = _addToCartButton.right;
    _buyNowButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _buyNowButton.frame = CGRectMake(x, y, width, height);
    _buyNowButton.backgroundColor = RED_COLOR;
    [_buyNowButton setTitle:@"立即购买" forState:UIControlStateNormal];
    [_buyNowButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_buyNowButton addTarget:self action:@selector(buyNowAction:) forControlEvents:UIControlEventTouchUpInside];
    [_popView addSubview:_buyNowButton];
}

// 创建商品列表视图
- (void)_createCollectionView {
    
    _selectCount = 1;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 15;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(5, 15, 5, 15);
//    layout.estimatedItemSize = CGSizeMake(1, 1);

    // 设置滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

    CGFloat x = 0;
    CGFloat y = _iconView.bottom + 10;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = _popView.height - y - _confirmButton.height;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(x, y, width, height) collectionViewLayout:layout];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_popView addSubview:_collectionView];
    
    // 注册单元格
    // 展示规格的单元格
    [_collectionView registerClass:[CollectSkuCell class] forCellWithReuseIdentifier:@"CollectSkuCell"];

    // 选择数量的单元格
    [_collectionView registerClass:[AmountCell class] forCellWithReuseIdentifier:@"AmountCell"];
    // 注册头视图
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
}

#pragma mark - collectionView 代理
// 定义展示的UICollectionViewCell的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _skuNameAry.count + 1;
}
// 定义展示的Section的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == _skuNameAry.count) {
        return 1;
    } else {
        SkuNameModel *model = _skuNameAry[section];
        return model.vidAry_des.count;
    }
    
}
// 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 最后一行 选择数量的单元格
    if (indexPath.section == _skuNameAry.count) {
        AmountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AmountCell" forIndexPath:indexPath];
        // 初始设置数量为1
        AmountModifyView *amountView = (AmountModifyView *)[cell.contentView viewWithTag:100];
        amountView.delegate = self;
        amountView.amount = _selectCount;
        return cell;
    } else {
        CollectSkuCell *cell = (CollectSkuCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectSkuCell" forIndexPath:indexPath];
  
        // 1.数据展示
        SkuNameModel *model = _skuNameAry[indexPath.section];
        NSString *text = model.vidAry_des[indexPath.row];
        cell.labelSort.text = text;
        //根据字数设置字体
        if ([text getSizeOfString:14].width > 100) {
            cell.labelSort.font = FONT(12);
            if ([text getSizeOfString:12].width > 100 ) {
                cell.labelSort.font = FONT(10);
                if ([text getSizeOfString:10].width > 100) {
                    cell.labelSort.font = FONT(8);
                }
            }
        }
       
        // 2.collection颜色变化
        // 选择中模型
        SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
        cell.tag = indexPath.row;
        cell.userInteractionEnabled = YES;
        
        // 获得该row的单元格是否可点击
        BOOL isAble = [selectModel.isableTouchCollectArray[indexPath.row] boolValue];
        if (!isAble) {
            cell.userInteractionEnabled = NO; // 不可点击的单元格做处理
        }
        
        // 3.cell处理（单元格背景颜色和字体颜色变化）
        [cell showSelectCollectionRow:selectModel];

        return cell;
    }

}
// 单元格的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 选择数量的单元格
    if (indexPath.section == _skuNameAry.count) {
        return CGSizeMake(SCREEN_WIDTH, 50);
    } else {
        // 动态设置单元格尺寸
//        SkuNameModel *model = _skuNameAry[indexPath.section];
//        NSString *text = model.vidAry_des[indexPath.row];
//        CGFloat width = [text getSizeOfString:14].width + 20;
//        CGFloat height = 30;
//        return CGSizeMake(width, height);
        CGFloat margin = 16;
        return CGSizeMake((SCREEN_WIDTH - margin * 4)/3, 30);

    }
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == _skuNameAry.count) {
        return UIEdgeInsetsZero;
    } else {
        return UIEdgeInsetsMake(5, 15, 5, 15);
    }
}
// 头视图的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == _skuNameAry.count) {
        return CGSizeZero;
    }
    return CGSizeMake(SCREEN_WIDTH, 30);
}
// 设置头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableview = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *headerView = (UICollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
        label.font = FONT(14);
        label.textColor = [UIColor darkGrayColor];
        label.textAlignment = NSTextAlignmentLeft;
        [headerView addSubview:label];
        label.tag = 1;
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
        line.top = 0;
        [headerView addSubview:line];
        line.hidden = YES;
        line.tag = 2;
        
        reusableview = headerView;
        
    }
    // 对于不是添加的那一组的组头做处理
    if (indexPath.section != _skuNameAry.count) {
        // 显示规格标题
        UILabel *label = (UILabel *)[reusableview viewWithTag:1];
        SkuNameModel *model = _skuNameAry[indexPath.section];
        label.text = model.sid_des;
        // 显示线
        UIView *line = [reusableview viewWithTag:2];
        line.hidden = NO;
        
        return reusableview;
    }
    
    return nil;
}

// 单元格选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == _skuNameAry.count) {
        return; // 点击到了最后一行就直接返回
    }
    
    // _skuSelectModelArray 有多少分区就有多少selectModel的对象，对的对应组的该对方，判断当前点击是否可点
    SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
    BOOL isAble = [selectModel.isableTouchCollectArray[indexPath.row] boolValue];
    
    // 不能点击
    if (!isAble) {
        return;
    }
    // 能点击
    else {
        // 初始化 _skuSelectModelArray ，使 bool为YES，然后再判断赋值
        for (NSInteger i = 0  ; i < _skuSelectModelArray.count; i ++) {
            SkuCellSelectModel *selectModel = [_skuSelectModelArray objectAtIndex:i];
            
            [selectModel changeStateOfTouchCollectArray:YES];
        }
    }
    
    // **** 记录当前collection的选择状态（SkuCellSelectModel），为后面刷新collecView时规格状态改变铺路  ***
    NSString *keyID = nil;
    if (selectModel.selectRow == indexPath.row) {
        selectModel.selectRow = -1;
        selectModel.selectSection = -1;
        NSLog(@"同一个单元格");
        // 默认字符串 sku_id:
        keyID = [ProductInfoHandle getDefaultNoIDString];
        
    } else {
        // 当前单元格对应ID（46：128）
        keyID = [ProductInfoHandle getCurrCollectSkuId:indexPath skuIdModel:_skuIdAry[indexPath.section]];
        NSLog(@"当前单元格的skuId:%@", keyID);
        // 刷新
        [selectModel reloadSelectRow:indexPath.row section:indexPath.section];
    }
    
    // 2.改变保存的skuKeyID
    [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:keyID];
    
    // 3.做判断，选择是否合法（是否可以组成完成的sku_id）--- isAble
    [ProductInfoHandle isUseableSkuIdArray:_skuSelectIdArray complete:^(BOOL isable) {
        
        if (isable) {  //如果所有规格都选择了，查找选择的模型
            
            // 去掉当前选择的组的另外的组
            NSArray *selecKeyValuetArray = [ProductInfoHandle getSelectSkuIDList:_skuSelectIdArray except:indexPath.section];
            
            // 预测当前点击的组中可点击的单元格
            [self getOnlyOneSkuNotSelectCollectIndex:selecKeyValuetArray index:indexPath.section];
            
            // 根据规格ID找到对应商品
            SkuModel *model = [self getSelectSkuModel];
            if (model != nil ) {  //展示商品详情信息
            
                [self productAttributeLayout:model]; // 商品属性修改（库存等）
                
                // 找到了正确的商品
                _selectedModel = model;
            }
            // 如果没有找到，或者库存为0，都要把当前sku_id,改掉
            if (model == nil || [model.quantity boolValue] == 0) {
                
                [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:[ProductInfoHandle getDefaultNoIDString]];
                
                SkuCellSelectModel *selectModel = _skuSelectModelArray[indexPath.section];
                [selectModel reloadSelectRow:-1 section:indexPath.section];
                
                //找到的规格模型不可用，展示详情
                [self productAttributeLayout:nil]; // 商品属性修改（库存等）
                
                // 该商品库存为0
                _selectedModel = nil;
            }
        }
        //返回还没有被选择的分区下标:"0" "1",
    } noSelectAry:^(NSArray *notSeletSectionArray) {
        
        // 如果只有一个分区没有被选中
        if (notSeletSectionArray.count == 1) {

            // selectedSkuIdAry:是除了未赋值的所有skuId的数组
            // 而_skuSelectIdArray是包含了未赋值的所有的skuId的数组
            NSArray *selectedSkuIdAry = [ProductInfoHandle getSelectedSkuIdAry:_skuSelectIdArray];
            
            // 获得没被选择的组的索引（section）
            NSInteger section = [[notSeletSectionArray lastObject] integerValue];
            
            [self getOnlyOneSkuNotSelectCollectIndex:selectedSkuIdAry index:section];
        }
        
        //规格没找到展示商品详情
        [self productAttributeLayout:nil];
        
        // 没有选择全部的规格
        _selectedModel = nil;
    }];
    
    // TODO: 选中的skuid数组（1：3，2：4），可以拼接成sku_id（1：3；2：4；）然后可以获得详细的商品
    NSLog(@"****keyIdAry*****:%@ \n选中的商品sku_id:%@", _skuSelectIdArray, _selectedModel.sku_id);

    //5 ,刷新
    [_collectionView reloadData];
}


#pragma mark - 点击事件
// 点击取消按钮
- (void)cancelAction:(UIButton *)button {
    [self hidden];
}
// 确定
- (void)confirmAction:(UIButton *)button {
    switch (_btnType) {
        case BtnTypeForAddToShopCar:
        {
            [self addToCartAction:nil];
        }
            break;
        case BtnTypeForBuyNow:
        {
            [self buyNowAction:nil];
        }
            break;
            
        default:
            break;
    }
}
// 加入购物车
- (void)addToCartAction:(UIButton *)button {

    if (_selectedModel == nil) { // 没有正确的选中商品
        [SVProgressHUD showErrorWithStatus:@"请选择正常的商品规格" withDuration:1.5];
        return;
    } else {
        // 获得商品数量
//        AmountCell *amountCell = (AmountCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:_skuNameAry.count]];
//        AmountModifyView *amountView = (AmountModifyView *)[amountCell.contentView viewWithTag:100];
        // 未加载数量单元格
//        if (amountView == nil) {
//            amount = 1;
//        } else {
//            amount = [amountView getAmount];
//        }
        if (_selectCount == 0) {
            [SVProgressHUD showErrorWithStatus:@"商品数量不能为0" withDuration:1.5];
            return;
        }
       
        // 用户信息用于获得uid
        UserModel *user = [CommonCache getUserInfo];
        if (user == nil) { // 未登录
//            _selectedModel = nil;
            LoginVC *vc = [[LoginVC alloc] init];
            BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
            [self.viewController presentViewController:naviVc animated:YES completion:nil];
            return;
        }
        NSDictionary *params = @{@"uid":user.uid,               // 用户id
                                 @"p_id":_detailModel.p_id,     // 商品id
                                 @"count":@(_selectCount),            // 数量
                                 @"psku_id":_selectedModel._id, // 规格id
                                 };
        
        [SVProgressHUD showWithStatus:@"正在为您添加入购物车..." maskType:SVProgressHUDMaskTypeClear];
        [BoyeHttpClient post:@"BY_ShoppingCart_add" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
            [SVProgressHUD showSuccessWithStatus:@"添加购物车成功" withDuration:1.5];
            // 把选中model设为nil
//            _selectedModel = nil;
            [self hidden];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"加入购物车_error:%@", error);
//            [SVProgressHUD showErrorWithStatus:@"添加购物车失败"];
            [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];

        }];
    }
}
// 立即购买
- (void)buyNowAction:(UIButton *)button {
    if (_selectedModel == nil) { // 没有正确的选中商品
        [SVProgressHUD showErrorWithStatus:@"请选择正常的商品规格" withDuration:1.5];
        return;
    } else {
        // 获得商品数量
//        AmountCell *amountCell = (AmountCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:_skuNameAry.count]];
//        AmountModifyView *amountView = (AmountModifyView *)[amountCell.contentView viewWithTag:100];
// 未加载数量单元格
//        if (amountView == nil) {
//            amount = 1;
//        } else {
//            amount = [amountView getAmount];
//        }
        if (_selectCount == 0) {
            [SVProgressHUD showErrorWithStatus:@"商品数量不能为0" withDuration:1.5];
            return;
        }
        
        // 用户信息用于获得uid
        UserModel *user = [CommonCache getUserInfo];
        if (user == nil) { // 未登录
            LoginVC *vc = [[LoginVC alloc] init];
            BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
            [self.viewController presentViewController:naviVc animated:YES completion:nil];
            return;
        }
        NSDictionary *params = @{@"uid":user.uid,               // 用户id
                                 @"p_id":_detailModel.p_id,     // 商品id
                                 @"count":@(_selectCount),            // 数量
                                 @"psku_id":_selectedModel._id, // 规格id
                                 };

        // 先把商品添加到购物车
        [SVProgressHUD showWithStatus:@"正在检测订单状态..." maskType:SVProgressHUDMaskTypeClear];
        [BoyeHttpClient post:@"BY_ShoppingCart_add" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
            NSLog(@"%@", result);
            NSString *_id = result;
            
            //更新购物车数量
            [BoyeHttpClient post:@"BY_ShoppingCart_edit" apiVerson:100 params:@{@"id":result, @"count":@(_selectCount)} success:^(AFHTTPRequestOperation *operation, id result) {
                
                
                // 根据购物车id，单个查询商品，在把这个商品传到确认订单页面
                [BoyeHttpClient post:@"BY_ShoppingCart_getinfo" apiVerson:100 params:@{@"id":_id} success:^(AFHTTPRequestOperation *operation, id result) {
                    //                [SVProgressHUD dismiss];
                    // 把选中model设为nil
                    //                _selectedModel = nil;
                    //                [self hidden];
                    CartProductModel *model = [[CartProductModel alloc] initContentWithDic:result];
                    
                    // 获得店铺推荐数据（传到订单确认页面）
                    [BoyeHttpClient post:@"BY_StorePromotion_getInfo" apiVerson:100 params:@{@"store_id":@2} success:^(AFHTTPRequestOperation *operation, id result) {
                        
                        [SVProgressHUD dismiss];
                        [self hidden];
                        
                        StoreDiscountModel *discountModel = nil;
                        
                        // 有数据，对于没数据的直接传给确认订单页面一个nil就好了
                        if (![result isKindOfClass:[NSNull class]]) {
                            discountModel = [[StoreDiscountModel alloc] initContentWithDic:result];
                            
                            // 如果当前时间不在优惠时间区间内，则不给予优惠
                            if (!([[NSDate currentTimeStamp] integerValue] >= [discountModel.start_time integerValue] && [[NSDate currentTimeStamp] integerValue] <= [discountModel.end_time integerValue])) {
                                discountModel = nil;
                            }
                            
                            // 获得该商品对应于购物车id的
                            ConfirmOrderVC *vc = [[ConfirmOrderVC alloc] init];
                            vc.itemsAry = @[model];
                            vc.discountModel = discountModel;
                            [self.viewController.navigationController pushViewController:vc animated:YES];
                        }
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
                    }];
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"查询单个购物车商品_error:%@", error);
                    //                [SVProgressHUD showErrorWithStatus:@"购买失败"];
                    [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
                    
                }];

                
                
                
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
            }];

            
            
            
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"加入购物车_error:%@", error);
//            [SVProgressHUD showErrorWithStatus:@"购买失败"];
            [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];

        }];
    }
}


#pragma mark - 数量修改 代理
- (void)amountDidModified:(NSInteger)amount {
    NSLog(@"商品数量 %li", (long)amount);
    _selectCount = amount;
}


#pragma mark - 其他方法（代码太多，写成代码块方法）
// 根据选中的id字符串 找到对应的商品
- (SkuModel *)getSelectSkuModel {
    
    NSString *fullSkuId = [ProductInfoHandle getFullSkuId:_skuSelectIdArray];
    //根据sku_id 找规格模型
    SkuModel *model = [ProductInfoHandle findSkuModelInSkuAry:_detailModel.skuAry fullSkuId:fullSkuId];
    
    return model;
}
- (void)getOnlyOneSkuNotSelectCollectIndex:(NSArray *)selecKeyValuetAry index:(NSInteger )section{
    
    /**
     没有选择的分区的处理
     找到预测分区中不可点击的row并记录下来
     */
    [ProductInfoHandle forecastSkuIdIsable:_detailModel selectedSkuIdAry:selecKeyValuetAry section:section disAbleBlock:^(NSArray *disTouchSkuIDArray) {
        
        // 获得该组对应的规格选择模型（用于重置可选数组）
        SkuCellSelectModel *selectModel = [_skuSelectModelArray objectAtIndex:section];
        
        // 如果不可选数组为空，则该组的单元格全部可选
        if (disTouchSkuIDArray.count == 0 || disTouchSkuIDArray == nil) {
            [selectModel changeStateOfTouchCollectArray:YES];
        } else {
            SkuIdModel *model = _skuIdAry[section];
            // 如果不可选数组中有（47:129），而该组的整个规格有（47:129 ; 47:130），则找出索引为0并设置不可选
            for (NSString *key in disTouchSkuIDArray) {
                NSInteger index = [model getKeyValueIndex:key];
                [selectModel.isableTouchCollectArray replaceObjectAtIndex:index withObject:@NO];
            }
        }
    }];
}

// 商品图片，价格，库存，规格视图重新布局
- (void)productAttributeLayout:(SkuModel *)model {
    // 如果传入了具体的规格model，则用规格model去赋值
    if (model != nil) {
//        NSString *img_prefix = @"http://sunsun.itboye.com/index.php/Api/Picture/index?id=";
        NSString *img_id = [model.icon_url stringByReplacingOccurrencesOfString:BOYE_PICTURE_URL withString:@""];
        NSLog(@"规格model:%@", img_id);
        // 设置商品图片
        if ([img_id isEqualToString:@""]) {

            [_iconView setImageURLStr:_detailModel.main_img placeholder:DEFAULT_IMAGE];
        } else {
            [_iconView setImageURLStr:model.icon_url placeholder:DEFAULT_IMAGE];
        }
        // 设置价格
        _priceLabel.text = [NSString stringWithFormat:@"￥%@", model.price];
        // 设置库存
        _stockLabel.text = [NSString stringWithFormat:@"库存%@件", model.quantity];
        // 设置规格注释
        _notesLabel.text = [NSString stringWithFormat:@"%@", model.sku_desc];
    }
    // 如果传入的是nil，则用商品详情的属性去填充
    else {
        // 设置商品图片
        [_iconView setImageURLStr:_detailModel.main_img placeholder:DEFAULT_IMAGE];
        // 设置价格
        if ([_detailModel.has_sku integerValue]) { // 有多规格，则可能有最低价和最高价
            if (![_detailModel.min_price isEqualToString:_detailModel.max_price]) {
                _priceLabel.text = [NSString stringWithFormat:@"￥%@-%@", _detailModel.min_price, _detailModel.max_price];
            } else {
                _priceLabel.text = [NSString stringWithFormat:@"￥%@", _detailModel.min_price];
            }
        } else {
            _priceLabel.text = [NSString stringWithFormat:@"￥%@", _detailModel.min_price];
        }
        // 设置库存
        NSInteger allStock = 0;
        for (SkuModel *skuModel in _detailModel.skuAry) {
            allStock += [skuModel.quantity integerValue];
        }
        _stockLabel.text = [NSString stringWithFormat:@"库存%li件", (long)allStock];
        // 设置规格注释
        _notesLabel.text = [NSString stringWithFormat:@"请选择规格"];
    }
    
}

#pragma mark - 重写set
// 隐藏立即购买和加入购物车
- (void)setIsOnlyConfirm:(BOOL)isOnlyConfirm {
    
    _confirmButton.hidden = !isOnlyConfirm;
    _addToCartButton.hidden = isOnlyConfirm;
    _buyNowButton.hidden = isOnlyConfirm;
}
// 数据设置
// 规格内容数组
- (void)setSkuNameAry:(NSArray<SkuNameModel *> *)skuNameAry {
    _skuNameAry = skuNameAry;
    
    _skuSelectModelArray = [[NSMutableArray alloc] init];
    for (int i = 0;  i < _skuNameAry.count; i ++) {

        SkuCellSelectModel *model = [[SkuCellSelectModel alloc] init];
        SkuNameModel *skuNameModel =  _skuNameAry[i];
        model.rowCount = skuNameModel.vidAry_des.count;
        model.currentSection = i;
        [_skuSelectModelArray addObject:model];
    }
    
    [_collectionView reloadData];
    
}
// 规格id数组
- (void)setSkuIdAry:(NSArray<SkuIdModel *> *)skuIdAry {
    _skuIdAry = skuIdAry;
    
    _skuSelectIdArray = [[NSMutableArray alloc] init];
    
    for (int i = 0;  i < _skuIdAry.count; i ++) {
        
        NSString *keyId = [ProductInfoHandle getDefaultNoIDString];
        [_skuSelectIdArray addObject:keyId];
    }

}
// 规格列表数组
- (void)setSkuAry:(NSArray<SkuModel *> *)skuAry {
    _skuAry = skuAry;
    
    if (_skuAry.count == 1) { // 表示统一规格
        _selectedModel = [_skuAry firstObject];
    }
}
// 商品详情
- (void)setDetailModel:(ProductDetailModel *)detailModel {
    _detailModel = detailModel;
    
    // 刚进入的时候，用商品详情的内容去填充规格属性
    [self productAttributeLayout:nil];
}

- (void)resetSelected {
    
}


#pragma mark - 全局方法
// 显示弹出视图
- (void)show {
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        _bgView.alpha = 0.5;
        _popView.bottom = self.height;
    }];
    
    
}
// 隐藏弹出视图
- (void)hidden {
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.alpha = 0;
        _popView.top = self.height;
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

@end
